package com.itheima.web.servlet;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Route;
import com.itheima.factory.BeanFactory;
import com.itheima.service.RouteService;
import com.itheima.service.impl.RouteServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/routeServlet")
public class RouteServlet extends BaseServlet {

    //RouteService routeService = new RouteServiceImpl();
    RouteService routeService = (RouteService) BeanFactory.getBean("routeService");

   /* @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        String action = req.getParameter("action");
        if (StringUtils.equals(action, "findByCid")) {
            findByCid(req, resp);
        }
    }*/


    private void findByCid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer cid = Integer.parseInt(req.getParameter("cid"));

        List<Route> routeList = routeService.findByCid(cid);

        String value = new ObjectMapper().writeValueAsString(routeList);
        resp.getWriter().write(value);
    }

    private void findRouteDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer rid = Integer.parseInt(req.getParameter("rid"));

        Route route = routeService.findRouteDetail(rid);

        String value = new ObjectMapper().writeValueAsString(route);
        System.out.println(value);
        resp.getWriter().write(value);
    }

}
